package com.ctcc.controller;


import com.alibaba.fastjson.JSONObject;
import com.ctcc.entity.count.*;
import com.ctcc.serviceImpl.CountImpl;
import com.ctcc.serviceImpl.ProductListImpl;
import com.ctcc.serviceImpl.UserImpl;
import com.ctcc.util.AccessTokenService;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.mobile.device.Device;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * Created by Peanut on 2018/2/24.
 */
@Controller
@RequestMapping("/pc")
public class CountToPcController {
    @Autowired
    private CountImpl countImpl;
    @Autowired
    AccessTokenService accessTokenService;
    @Autowired
    private UserImpl userImpl;
    private User user= new User();
//    private volatile String userTicket;

    @Autowired
    private ProductListImpl productListImpl;

    Log log= LogFactory.getLog(CountToPcController.class);

    /***
     * 云计算页面
     * @param model
     * @return
     */
    @GetMapping(value = "/getCount/{openId}/")
    public String index(ModelMap model,
                        @PathVariable String openId,
                        @RequestParam(value = "ticket",required = false) String ticket)
            throws  IOException ,ExecutionException { // 加入一个属性，用来在模板中读取
        model.put("memoryList",countImpl.getMemoryKind(1l));
        model.put("memoryShop",countImpl.getAllMemShop());
        //设置页面的标题
        model.put("title","云主机");
        model.put("openId",openId);
        return "pc/appcount";
    }


    /**
     * 更据CPU类型得到db内存
     */
    @GetMapping(value = "/getDbType/{cid}")
    @ResponseBody
    public Object getDbMemoryKind(@PathVariable Long cid){
        JSONObject jsonObject =new JSONObject();

//        if(StringUtils.isNotEmpty(toString().valueOf(cid))) ;

        List<DbZhuBeiMemory> dbMemoryList= countImpl.getDbMemoryKind(cid);
        jsonObject.put("dbMemoryList",dbMemoryList);
        return jsonObject;
    }



    /**
     * 更据CPU类型得到只读db内存
     */
    @GetMapping(value = "/getDbTwoType/{cid}")
    @ResponseBody
    public Object getDbTwoMemoryKind(@PathVariable Long cid){
        JSONObject jsonObject =new JSONObject();
//        if(StringUtils.isNotEmpty(toString().valueOf(cid))) ;

        List<DbZhiDuMemory> dbZhiduMemoryList= countImpl.getDbZhiDuMemoryKind(cid);
        jsonObject.put("dbZhiduMemoryList",dbZhiduMemoryList);
        return jsonObject;
    }





    /**
     * 更据CPU类型得到内存
     */
    @GetMapping(value = "/search/{cid}")
    @ResponseBody
    public Object getMemoryKind(@PathVariable Long cid){
        JSONObject jsonObject =new JSONObject();

//        if(StringUtils.isNotEmpty(toString().valueOf(cid))) ;

        List<Memory> memoryList= countImpl.getMemoryKind(cid);
        jsonObject.put("memoryList",memoryList);
        return jsonObject;
    }
    @GetMapping(value = "/getPrice/{cpuVal}/{memVal}")
    @ResponseBody
    public  Object getPrice(@PathVariable Long cpuVal,@PathVariable String memVal ){
        JSONObject jsonObject =new JSONObject();
//        if(StringUtils.isNotEmpty(memVal)&&StringUtils.isNotEmpty(toString().valueOf(cpuVal)));
        Memory memory=countImpl.getPrice(cpuVal,memVal);
        jsonObject.put("price", memory);
        return jsonObject;

    }



    @GetMapping(value = "/getDbPrice/{cpuVal}/{memVal}")
    @ResponseBody
    public  Object getDbPrice(@PathVariable Long cpuVal,@PathVariable String memVal ){
        JSONObject jsonObject =new JSONObject();
//        if(StringUtils.isNotEmpty(memVal)&&StringUtils.isNotEmpty(toString().valueOf(cpuVal)));
        DbZhuBeiMemory price=countImpl.getDbZbPrice(cpuVal,memVal);
        jsonObject.put("price", price);
        return jsonObject;

    }

    @GetMapping(value = "/getDbZdPrice/{cpuVal}/{memVal}")
    @ResponseBody
    public  Object getDbZdPrice(@PathVariable Long cpuVal,@PathVariable String memVal ){
        JSONObject jsonObject =new JSONObject();
//        if(StringUtils.isNotEmpty(memVal)&&StringUtils.isNotEmpty(toString().valueOf(cpuVal)));
        DbZhiDuMemory prices=countImpl.getDbZdPrice(cpuVal,memVal);
        jsonObject.put("price", prices);
        return jsonObject;

    }




    @GetMapping(value = "/updateproductcheckstate/{itemId}/{checkState}")
    @ResponseBody
    public  Object upDateCheckState(@PathVariable Long itemId,@PathVariable String checkState){
        JSONObject jsonObject =new JSONObject();
//        if(StringUtils.isNotEmpty(toString().valueOf(itemId))&&StringUtils.isNotEmpty(checkState));
        productListImpl.upDateCKState(itemId,checkState);
        jsonObject.put("state", "success");
        return jsonObject;

    }

    @GetMapping(value = "/updateAllProductState/{checkState}/{openId}")
    @ResponseBody
    public  Object upDateAllState(@PathVariable String checkState,@PathVariable String openId){
        JSONObject jsonObject =new JSONObject();
//        if(StringUtils.isNotEmpty(openId)&&StringUtils.isNotEmpty(checkState));
        productListImpl.upDateAllState(openId,checkState);
        jsonObject.put("state", "success");
        return jsonObject;

    }

    @GetMapping(value = "/removeitem/{itemId}")
    @ResponseBody
    public  Object upDateAllState(@PathVariable Long itemId){
        JSONObject jsonObject =new JSONObject();
        productListImpl.deleteById(itemId);
        jsonObject.put("state", "success");
        return jsonObject;

    }


    @GetMapping(value = "/changecount/{openId}/{discont}/")
    @ResponseBody
    public  Object changeCount(@PathVariable String openId,@PathVariable String discont){
        JSONObject jsonObject =new JSONObject();
        productListImpl.changeCount(openId,discont);
        jsonObject.put("state", "success");
        return jsonObject;

    }




    @GetMapping(value = "/updateproductcount/{itemId}/{count}")
    @ResponseBody
    public  Object updateCount(@PathVariable Long  itemId,@PathVariable String count){
        JSONObject jsonObject =new JSONObject();
//        if(StringUtils.isNotEmpty(count));
        productListImpl.upDateCount(itemId,count);
        jsonObject.put("state", "success");
        return jsonObject;

    }

    @GetMapping(value = "/index/{openId}/")
    public String  toIndex(ModelMap model,@PathVariable String  openId) throws IOException,ExecutionException{
        model.put("openId",openId);
        model.put("title","价格计算器");
        return "pc/index";
    }



    @GetMapping(value = "/index/")
    public String  getIndex(ModelMap model,
                            Device device,
                            @RequestParam(value = "ticket",required = false) String ticket,
                            HttpServletRequest request) throws IOException,ExecutionException{
//        String ticket = request.getParameter("ticket");
        if(StringUtils.isNotEmpty(ticket)){
            String openId=getUser(ticket);
            if(userImpl.getUserByOpenId(openId)==null){
                User user=new User();
                user.setOpenId(openId);
                user.setUserName(accessTokenService.getUserInfo(accessTokenService.getToken(),ticket).getUsername());
                userImpl.saveUser(user);
                model.put("openId",openId);
            }
            else {
                user=userImpl.getUserByOpenId(openId);
                model.put("openId",user.getOpenId());
            }
            model.put("title","价格计算器");
            return "pc/index";
        }else{
            //打印请求链接
            log.info(device.getDevicePlatform().name());
            log.info(request.getHeader("User-Agent"));
            log.info(request.getRequestURI());
            log.info(request.getQueryString());
            return "redirect:https://yunzhijia.com/space/c/app";
        }

    }

    @GetMapping(value = "/accessToken")
    public HttpEntity getAccessToken(){
        try {
            return ResponseEntity.ok(accessTokenService.getToken());
        } catch (IOException | ExecutionException e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }


    /**
     * 得到当前用户openId
     */

    public String  getUser(String ticket) throws IOException,ExecutionException{
        //return accessTokenService.getUserInfo(accessTokenService.getToken(),userTicket);
        System.out.println(accessTokenService.getToken());
//        System.out.println(userTicket);
       return accessTokenService.getUserInfo(accessTokenService.getToken(),ticket).getOpenid();
    }

    /***
     * 更据当前操作人
     * 将自己所选的产品
     * 加入清单
     * @param openId
     * @return
     * @throws IOException
     * @throws ExecutionException
     */
    @PostMapping(value ="/takeList/{openId}/")
    @ResponseBody
    public Object saveList(@PathVariable String openId,HttpServletRequest request) throws IOException,ExecutionException{
        String cpu=request.getParameter("cpuAndMem");
        String memory=request.getParameter("meMory");
        String productTitleOne=cpu+"  "+memory;
        String productTitleTwo=request.getParameter("stat");
        String productTitleThree=request.getParameter("brandNum");
        String productPriceTy=request.getParameter("all_price");
        String productPriceAli=request.getParameter("ali_price");
        String productPriceTx=request.getParameter("tx_price");
        String productTypeId=request.getParameter("productTypeId");
        String discount=request.getParameter("disCount");
        String productName=request.getParameter("productName");
        String titleOneKey=request.getParameter("oneKey");
        String twoKey=request.getParameter("twoKey");
        String threeKey=request.getParameter("threeKey");

        String oneImage=request.getParameter("oneImage");
        String twoImage=request.getParameter("twoImage");
        String threeImage=request.getParameter("threeImage");
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("msg","添加失败");
        //在新增的时候查询一次，如果有就将数量加一
        ProductList oldProductList=productListImpl.getProduct(openId,productPriceTy,productName,productTypeId);
        if(oldProductList!=null&&oldProductList.getId()>0){
             String count=oldProductList.getProductCount();

             int addCount=Integer.parseInt(count);

            addCount=addCount+1;
            String newCount=String.valueOf(addCount);
            productListImpl.upDateCount(oldProductList.getId(),newCount);
            jsonObject.put("type","success");
            jsonObject.put("msg","添加成功");
        }
        else {
            //否则为新增
            //将值放到对象中

            ProductList productList=new ProductList();
            if(!"4".equals(productTypeId)){
                productList.setDisCount(1F);
            }
            else {
                productList.setDisCount(Float.parseFloat(discount));
            }
            productList.setOpenId(openId);
            productList.setProductCount("1");
            productList.setProductPriceAli(productPriceAli);
            productList.setProductPriceTx(productPriceTx);
            productList.setProductPriceTy(productPriceTy);
            productList.setProductName(productName);
            productList.setProductTitleOneKey(titleOneKey);
            productList.setProductTitleThreeKey(threeKey);
            productList.setProductTitleTwoKey(twoKey);
            productList.setProductTitleOne(productTitleOne);
            productList.setProductTitleTwo(productTitleTwo);
            productList.setProductTitleThree(productTitleThree);
            productList.setTitleOneImage(oneImage);
            productList.setTitleTwoImage(twoImage);
            productList.setTitleThreeImage(threeImage);
            productList.setProductTypeId(productTypeId);
            productList.setCheckState("0");

            if(productListImpl.saveList( productList)){
                jsonObject.put("type","success");
                jsonObject.put("msg","添加成功");
            }
        }

        return jsonObject;

    }

    /**
     * 获取个人的清单
     */
    @GetMapping(value = "/getuserlist/{openId}/")
    public String getUserList( ModelMap model,@PathVariable String openId) throws  IOException,ExecutionException{
        List<ProductList> productLists=productListImpl.getUserList(openId);
        if(productLists!=null&&productLists.size()>0){
            model.put("count","1");
            model.put("productLists",productLists);
            model.put("openId",openId);
        }
        else {
            model.put("count","0");
            model.put("openId",openId);
        }
        model.put("title","清单");
        return "pc/list";
    }


    /**
     * 专属云页面
     */
    @RequestMapping("/getZhuan/{openId}/")
    public String zhuanShuYun(ModelMap model,@PathVariable String openId)  throws  IOException ,ExecutionException{ // 加入一个属性，用来在模板中读取

        model.put("openId",openId);
        model.put("title","专属云");
        return "pc/newzhuanshuyun";
    }


    /**
     * 物理机页面
     */
    @RequestMapping("/getWuLiJ/{openId}/")
    public String wuLiJi(ModelMap model,@PathVariable String openId) throws IOException,ExecutionException { // 加入一个属性，用来在模板中读取
        /*model.put("cpuTypeList",getCpuType());
        model.put("memoryList",countImpl.getMemoryKind(1l));*/
        //设置页面的标题
        model.put("openId",openId);
        model.put("title","物理机");
        return "pc/wuliji";
    }


    /**
     * 云专线页面
     */
    @RequestMapping("/getYunZx/{openId}/")
    public String yunZhuX(ModelMap model,@PathVariable String openId) throws IOException,ExecutionException { // 加入一个属性，用来在模板中读取

        //设置页面的标题
        model.put("openId",openId);
        model.put("title","云专线");
        return "pc/yunzhuanxian";
    }


    /**
     * 数据库页面
     */
    @RequestMapping("/getDb/{openId}/")
    public String dataBase(ModelMap model,@PathVariable String openId) throws IOException,ExecutionException { // 加入一个属性，用来在模板中读取
        //设置页面的标题
        model.put("openId",openId);
        model.put("title","关系型数据库");
        /*return "app/databases";*/
        return "pc/newdatabases";
    }



    /**
     * 漏洞扫描页面
     */
    @RequestMapping("/getScan/{openId}/")
    public String scanner(ModelMap model,@PathVariable String openId) throws IOException,ExecutionException { // 加入一个属性，用来在模板中读取
        //设置页面的标题
        model.put("openId",openId);
        model.put("title","漏洞扫描");
        return "pc/scanners";
    }



    /**
     * 漏洞扫描页面
     */
    @RequestMapping("/getSvpn/{openId}/")
    public String sllVpen(ModelMap model,@PathVariable String openId) throws IOException,ExecutionException { // 加入一个属性，用来在模板中读取
        //设置页面的标题
        model.put("openId",openId);
        model.put("title","SSL VPN");
        return "pc/sslVpn";
    }


    /**
     * 服务器安全页面
     */
    @RequestMapping("/getSecurity/{openId}/")
    public String security(ModelMap model,@PathVariable String openId) throws IOException,ExecutionException { // 加入一个属性，用来在模板中读取
        //设置页面的标题
        model.put("openId",openId);
        model.put("title","服务器安全");
        return "pc/security";
    }

    /**
     * 云备份页面
     */
    @RequestMapping("/getYunBf/{openId}/")
    public String yunBeiFen(ModelMap model,@PathVariable String openId) throws IOException,ExecutionException { // 加入一个属性，用来在模板中读取
        //设置页面的标题
        model.put("openId",openId);
        model.put("title","云备份");
        return "pc/yunbeifen";
    }




    /**
     * 云堡垒机页面
     */
    @RequestMapping("/getYunBl/{openId}/")
    public String baoLeiJi(ModelMap model,@PathVariable String openId) throws IOException,ExecutionException { // 加入一个属性，用来在模板中读取
        //设置页面的标题
        model.put("openId",openId);
        model.put("title","云堡垒机");
        return "pc/baoleiji";
    }



    /**
     * 对象存储页面
     */
    @RequestMapping("/getStore/{openId}/")
    public String Store(ModelMap model,@PathVariable String openId) throws IOException,ExecutionException { // 加入一个属性，用来在模板中读取
        //设置页面的标题
        model.put("openId",openId);
        model.put("title","对象存储");
        return "pc/store";
    }


    /**
     * 导出页面
     */
    @RequestMapping("/getList/{openId}/")
    public String getList(ModelMap model,@PathVariable String openId) throws IOException,ExecutionException { // 加入一个属性，用来在模板中读取
        //设置页面的标题
        model.put("openId",openId);
        model.put("title","清单");
        return "pc/tolist";
    }


    /**
     * 导出页面
     */
    @RequestMapping("/getUserList/{openId}/")
    public String getOneUserList(ModelMap model,@PathVariable String openId) throws IOException,ExecutionException { // 加入一个属性，用来在模板中读取
        //设置页面的标题
        model.put("openId",openId);
        model.put("title","清单");
        return "pc/tolist";
    }





    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
